from celery import current_app
from sqlalchemy.sql.functions import user

from info import constants
from info.models import News, User
from info.modules.news import news_blu
from flask import render_template, session, g, abort, request, jsonify

from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blu.route('/news_collect', methods = ["POST"])
@user_login_data
def collect_news():
    '''
    收藏新闻
    1.接受参数
    2.判断参数
    3.查询新闻判断是否存在
    :return:
    '''

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    news_id = request.json.get("news_id")
    action = request.json.get("action")

    if not news_id :
        return jsonify(errno=RET.PARAMERR, errmsg = "参数错误")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg = "参数错误")
    if action not in ["collect","cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询新闻判断是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e :
        return jsonify(errno=RET.DATAERR, errmsg="数据查询错误")
    if not news :
        return jsonify(errno=RET.NODATA, errmsg = "未查询到新闻数据")

    # 判断新闻是被收藏,如果没有收藏,就添加到收藏列表
    if action == "cancel_collect":
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            user.collection_news.append(news)

    return jsonify(error=RET.OK, errmsg="操作成功")


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    """
    新闻详情
    :param news_id:
    :return:
    """
    #判断是否登录
    user = g.user
    # user_id = session.get("user_id", None)
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 2.显示右边新闻排行
    news_list = []
    # news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    # 遍历对象列表，将对象列表添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 查询新闻数据
    news = None
    try :
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        abort(404)

    #更新点击次数
    news.clicks += 1

    # 收藏新闻的逻辑
    is_collected = False
    # if 用户已经登录
    #     判断是否收藏当前新闻
    if user:
        if news in user.collection_news:
            is_collected = True

    data = {
        "news_dict_li": news_dict_li,
        "user_info": user.to_dict() if user else None,
        "news" : news.to_dict(),
        "is_collected":is_collected,
    }


    return render_template("news/detail.html",data=data)
